package cn.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName: CuratorSenond
 * Desc:  异步接口 BackgroundCallback
 * Date： 2016/12/6
 * Created：shaom
 */
public class CuratorSenond {
    public static final String connectString = "master:2181,slave01:2181,slave02:2181";
    public static final String path = "/Curator";
    public static final String value = "CuratorValue";

    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(2000, 5))
            .build();
    static CountDownLatch downLatch = new CountDownLatch(2);
    static ExecutorService executor = Executors.newFixedThreadPool(2);


    public static void main(String[] args) throws Exception {
        client.start();

        System.out.println("Main thread : " + Thread.currentThread().getName());

        // 传入自定义的executor，异步逻辑会使用线程池去处理
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println("event[code:" + event.getResultCode() + ",type" + event.getType() + "]");
                        System.out.println("Thread of processResult:" + Thread.currentThread().getName());
                        downLatch.countDown();
                    }


                }, executor).forPath(path, "init".getBytes());


        // 会创建失败，默认使用EventThread 来处理
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                .inBackground(new BackgroundCallback() {
                    @Override
                    public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                        System.out.println("event[code:" + event.getResultCode() + ",type" + event.getType() + "]");
                        System.out.println("Thread of processResult:" + Thread.currentThread().getName());
                        downLatch.countDown();
                    }
                }).forPath(path, "init".getBytes());

        downLatch.await();
        executor.shutdown();
    }


}
